package com.cn.qtms.base.controller;//类注释设置模板

import com.cn.qtms.common.controller.BaseRestController;
import com.cn.qtms.common.result.Result;
import com.cn.qtms.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.JDBCException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.TransactionException;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Name:BaseJpaController
 * @Description:
 * @Author: zhangyang
 * @Date: 2019-11-13 22:07
 **/
@Slf4j
@RestController
public abstract class BaseJpaController extends BaseRestController {
    @Override
    public Result exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        if (e instanceof DataAccessException) {
            e = translateDataAccessException((DataAccessException) e);
        } else if (e instanceof TransactionException) {
            e = new SystemException("SE0005");
        } else if (e instanceof HibernateException) {
            e = translateHibernateException(e);
        }
        return super.exceptionHandler(request, response, e);
    }

    private SystemException translateDataAccessException(DataAccessException e) {
        Throwable cause = e.getCause();
        SystemException se = new SystemException("SE0002");
        if (cause instanceof ConstraintViolationException) {
            se = new SystemException("SE0004");
        } else if (cause instanceof JDBCException) {
            se = new SystemException("SE0002");
        }
        return se;
    }

    private SystemException translateHibernateException(Exception e) {
        SystemException se = new SystemException("SE0002");
        if (e instanceof ObjectNotFoundException) {
            se = new SystemException("SE0003", new String[]{((ObjectNotFoundException) e).getEntityName()});
        }
        return se;
    }
}
